package search

/**
 * @Description: 二分查找，前提是数组是有序的，升序
 * @Keyword: 左闭右闭
 * @Author: kami
 * @Date: 2022/6/22 13:28
 **/
func binary_search(nums []int, target int) int {
	var left = 0
	var right = len(nums) - 1 // 因为是由闭，所以right的值是下标最大值
	for left <= right {
		var mid = (left + right) / 2
		if nums[mid] > target {
			right = mid - 1
		} else if nums[mid] < target {
			left = mid + 1
		} else {
			return mid
		}
	}
	return -1
}

/**
 * @Description: 二分查找，前提是数组是有序的，升序
 * @Keyword: 左闭右开
 * @Author: kami
 * @Date: 2022/6/22 13:28
 **/
func binary_search1(nums []int, target int) int {
	var left = 0
	var right = len(nums) - 1 // 因为是由闭，所以right的值是下标最大值
	for left < right {
		var mid = (left + right) / 2
		if nums[mid] > target {
			right = mid
		} else if nums[mid] < target {
			left = mid + 1
		} else {
			return mid
		}
	}
	return -1
}
